package com.lh.arithmetic.interview.easyprogram;


/**
 ************************************************
 ** Module : 设计4个线程，其中两个线程每次对j增加1，
 ** 另外两个线程对j每次减少1。写出程序 些程序对变量是不安全的
 ** Date: 2013-3-15  Time: 下午04:04:51 
 ** Author lh 
 ************************************************ 
 */
public class TwoThreadIncTwoThreadDec {	
	public static void main(String[] args) {
		ChangeNumber c = new ChangeNumber(0);
		for(int i=0;i<5;i++){
			new Thread(new ThreadInc(c)).start();
		}
		for(int i=0;i<5;i++){
			new Thread(new ThreadDec(c)).start();
		}
        
	}

}
class ChangeNumber{
	int j=0;
	public ChangeNumber(int j){
		this.j = j;
	}
    public  synchronized void dec() {
		this.j--;
	}
    public  synchronized void inc() {
	   this.j++;
    }    
    public synchronized int getValue(){
    	return this.j;
    }
}

class ThreadInc implements Runnable{
	ChangeNumber temp = null;
	public ThreadInc(ChangeNumber cn){
		temp = cn;
	}
	@Override
	public void run() {
		int sleepTimer = (int) (Math.random() * 1000);
		this.temp.inc();
		System.out.println("ThreadInc "+Thread.currentThread().getId()+" "+
				Thread.currentThread().getName()+" j="+temp.getValue()+" sleeptime="+sleepTimer);
		try {
			Thread.sleep(sleepTimer);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class ThreadDec implements Runnable{
	ChangeNumber temp = null;
	public ThreadDec(ChangeNumber cn){
		temp = cn;
	}
	@Override
	public void run() {
		int sleepTimer = (int) (Math.random() * 1000);
		this.temp.dec();
		System.out.println("ThreadDec "+Thread.currentThread().getId()+" "+
				Thread.currentThread().getName()+" j="+temp.getValue()+" sleeptime="+sleepTimer);			
		try {			
			Thread.sleep(sleepTimer);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
}
